package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.*;
import com.itheima.domain.vo.ErrorResult;
import com.itheima.domain.vo.SettingVo;
import com.itheima.domain.vo.UserInfoVo;
import com.itheima.service.db.NotificationService;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service // spring的
public class UserManager {

    @Reference // dubbo的
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    // 保存用户
    public ResponseEntity save(User user) {
        Long userId = userService.save(user);
        return ResponseEntity.ok(userId);
    }

    // 根据手机号查询
    public ResponseEntity findByPhone(String phone) {
        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user);
    }

    public ResponseEntity sendSmsCode(String phone) { // TODO  产品上线前，开启短信发送
        // 1.生成验证码
        // String smsCode = RandomUtil.randomNumbers(6);
        String smsCode = "123456";

        // 2.发送短信
        // smsTemplate.sendSms(phone, smsCode);

        // 3.将验证码存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, smsCode, Duration.ofMinutes(5));

        return ResponseEntity.ok(null); // 返回状态码200，响应体空
    }

    public ResponseEntity regAndLogin(String phone, String verificationCode) {
        // 1.验证码比对
        // 从redis中获取
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        if (!StrUtil.equals(verificationCode, redisCode)) {
            // 对比不正确，返回错误提示
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        // 对比正确，清除验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        // 2.根据手机号查询
        User user = userService.findByPhone(phone);

        boolean isNew;
        String type = "0101"; // 登录
        if (user == null) {
            // 新用户
            isNew = true;
            // 完成注册
            user = new User();
            user.setPhone(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long userId = userService.save(user);
            user.setId(userId);

            // 同时向环信注册用户id
            huanXinTemplate.register(userId);
            type = "0102"; //  注册
        } else {
            // 老用户
            isNew = false;
        }


        // 向mq发送一条日志消息
        Log log = new Log();
        log.setUserId(user.getId());
        log.setType(type);
        log.setLogTime(DateUtil.formatDate(new Date()));
        log.setPlace("北京顺义"); // 课下去查询user_location
        log.setEquipment("华为mate40Pro");

        rocketMQTemplate.convertAndSend("tanhua-log", log);

        // 3.制作token（jwt技术）
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());
        String token = JwtUtil.createToken(claims);

        // 设置token续期时间，比如说5天
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set("token:" + token, json, Duration.ofDays(5));

        // 4.返回结果
        Map resultMap = new HashMap();
        resultMap.put("token", token);
        resultMap.put("isNew", isNew);
        return ResponseEntity.ok(resultMap);
    }

    public ResponseEntity saveUserInfoBase(UserInfo userInfo, String token) {
        // 1.解析token，获取user，续期token
        User user = findUserByToken(token);

        // 2.将userId封装到userInfo中
        userInfo.setId(user.getId());

        // 3.调用rpc保存
        userInfoService.save(userInfo);

        return ResponseEntity.ok(null);
    }

    // 解析token，获取user，续期token
    public User findUserByToken(String token) {
        // 从redis中获取
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        // 判断是否存在
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 如果存在转为user对象
        User user = JSON.parseObject(json, User.class);

        // 续期5天
        stringRedisTemplate.opsForValue().set("token:" + token, json, Duration.ofDays(5));
        return user;
    }

    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, String token) throws IOException {
        // 1.校验是否为人脸
        boolean isFace = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!isFace) {
            // 非人脸
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }

        // 2.oss图片上传
        String picPath = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        // 3.解析token获取user
        User user = findUserByToken(token);

        // 4.封装userInfo对象
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(picPath); // 头像
        userInfo.setCoverPic(picPath);  // 封面

        // 5.调用rpc完成更新
        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfoById(Long userID) {
        // 1.调用rpc查询
        UserInfo userInfo = userInfoService.findById(userID);
        // 2.封装vo
        UserInfoVo vo = new UserInfoVo();
        // 2-1 完成对象属性之间copy
        BeanUtil.copyProperties(userInfo, vo);
        // 2-2 手动设置年龄
        vo.setAge(userInfo.getAge().toString());
        // 3.返回vo对象
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfoBase(UserInfo userInfo, String token) {
        // 1.校验token是否有效（略）
        // 2.调用rpc完成更新
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }


}
